package com.qdlc.p2p.dal.mybatis.utils;

import java.math.BigDecimal;
import java.sql.Types;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl;

/**
 * 自定义BigDecimal类型的转换，将数据库中的BigDecimal处理成Java的Double类型
 *
 * @author linya
 */
public class DoubleJavaTypeResolver extends JavaTypeResolverDefaultImpl {

    @Override
    public FullyQualifiedJavaType calculateJavaType(
            IntrospectedColumn introspectedColumn) {
        FullyQualifiedJavaType answer;
        JdbcTypeInformation jdbcTypeInformation = typeMap.get(introspectedColumn.getJdbcType());

        if (jdbcTypeInformation == null) {
            switch (introspectedColumn.getJdbcType()) {
                case Types.DECIMAL:
                case Types.NUMERIC:
                    if (introspectedColumn.getScale() > 0 && !forceBigDecimals) {
                        answer = new FullyQualifiedJavaType(Double.class.getName());
                    } else if (introspectedColumn.getScale() > 0
                            || introspectedColumn.getLength() > 18
                            || forceBigDecimals) {
                        answer = new FullyQualifiedJavaType(BigDecimal.class
                                .getName());
                    } else if (introspectedColumn.getLength() > 9) {
                        answer = new FullyQualifiedJavaType(Long.class.getName());
                    } else if (introspectedColumn.getLength() > 4) {
                        answer = new FullyQualifiedJavaType(Integer.class.getName());
                    } else {
                        answer = new FullyQualifiedJavaType(Short.class.getName());
                    }
                    break;
                default:
                    answer = null;
                    break;
            }
        } else {
        	//重写数据库类型Integer情况，如果长度大于10，则设置成Long型
        	if(introspectedColumn.getJdbcType() == Types.INTEGER){
        		if(introspectedColumn.getLength() > 8){
            		answer = new FullyQualifiedJavaType(Long.class.getName());
            	}else{
            		answer = new FullyQualifiedJavaType(Integer.class.getName());
            	}
        	}else{
        		answer = jdbcTypeInformation.getFullyQualifiedJavaType();
        	}
        }

        return answer;
    }

}
